<?php

/**
 * This is the model class for table "tbl_user".
 *
 * The followings are the available columns in table 'tbl_user':
 * @property integer $id
 * @property string $name
 * @property string $login
 * @property string $email
 * @property string $activationKey
 * @property string $password
 * @property string $avatar
 * @property string $create_time
 * @property string $update_time
 * @property integer $create_user_id
 * @property integer $update_user_id
 * @property string $role
 * @property integer $active
 * @property string $login_time
 * @property string $last_login_time
 * @property string $verifyCode
 * @property string $password_repeat
 *
 * The followings are the available model relations:
 * @property Article[] $articles
 * @property Article[] $articles1
 * @property AuthItem[] $tblAuthItems
 * @property Category[] $categories
 * @property Category[] $categories1
 * @property Comment[] $comments
 * @property Comment[] $comments1
 * @property Rating[] $ratings
 */
class User extends UserActiveRecord
{
    public $password_repeat;
    public $userlogin;
    public $verifyCode;
	public $image;
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{user}}';
	}


	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(

            array('name,login,email,password,password_repeat','required','on'=>Yii::getPathOfAlias('application.modules.user.controllers.frontend.registration')),
            array('name,login,email,password','required','on'=>Yii::getPathOfAlias('modules.user.controllers.backend.create')),

			array('create_user_id, update_user_id, active', 'numerical', 'integerOnly'=>true),
			array('name, login, email, avatar,password', 'length', 'min'=>3, 'max'=>50),
			array('activationKey, password', 'length', 'max'=>40),
			array('role', 'length', 'max'=>20),
			array('create_time, update_time, login_time, last_login_time', 'safe'),
            array('password_repeat','compare','compareAttribute'=>'password','on'=>Yii::getPathOfAlias('application.modules.user.controllers.frontend.registration')),
            array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(),'on'=>Yii::getPathOfAlias('application.modules.user.controllers.frontend.registration')),
            array('email','email'),
            array('avatar', 'file','allowEmpty'=>true,'types'=>'jpg,jpeg,png,gif'),
            array('email','unique','attributeName'=>'email','className'=>'User'),
            array('login','unique','attributeName'=>'login','className'=>'User'),
            array('password,password_repeat', 'length','min'=>8),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, name, login, email, activationKey, password, avatar, create_time, update_time, create_user_id, update_user_id, role, active, login_time, last_login_time', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'articles' => array(self::HAS_MANY, 'Article', 'create_user_id'),
			'articles1' => array(self::HAS_MANY, 'Article', 'update_user_id'),
			'tblAuthItems' => array(self::MANY_MANY, 'AuthItem', 'tbl_auth_assignment(userid, itemname)'),
			'categories' => array(self::HAS_MANY, 'Category', 'update_user_id'),
			'categories1' => array(self::HAS_MANY, 'Category', 'create_user_id'),
			'comments' => array(self::HAS_MANY, 'Comment', 'update_user_id'),
			'comments1' => array(self::HAS_MANY, 'Comment', 'create_user_id'),
			'ratings' => array(self::HAS_MANY, 'Rating', 'create_user_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'name' => Yii::t('UserModule.base','name'),
			'login' => Yii::t('UserModule.base','Userlogin'),
			'email' => Yii::t('UserModule.base','Email'),
			'password' => Yii::t('UserModule.base','Password'),
			'password_repeat' => Yii::t('UserModule.base','Password Repeat'),
			'avatar' => Yii::t('UserModule.base','Avatar'),
			'create_time' => Yii::t('UserModule.base','create_time'),
			'update_time' => Yii::t('UserModule.base','update_time'),
			'create_user_id' => Yii::t('UserModule.base','create_user_id'),
			'update_user_id' => Yii::t('UserModule.base','update_user_id'),
			'role' => Yii::t('UserModule.base','role'),
			'active' => Yii::t('UserModule.base','active'),
			'login_time' => Yii::t('UserModule.base','login_time'),
			'last_login_time' => Yii::t('UserModule.base','last_login_time'),
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('login',$this->login,true);
		$criteria->compare('email',$this->email,true);
		$criteria->compare('activationKey',$this->activationKey,true);
		$criteria->compare('password',$this->password,true);
		$criteria->compare('avatar',$this->avatar,true);
		$criteria->compare('create_time',$this->create_time,true);
		$criteria->compare('update_time',$this->update_time,true);
		$criteria->compare('create_user_id',$this->create_user_id);
		$criteria->compare('update_user_id',$this->update_user_id);
		$criteria->compare('role',$this->role,true);
		$criteria->compare('active',$this->active);
		$criteria->compare('login_time',$this->login_time,true);
		$criteria->compare('last_login_time',$this->last_login_time,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
            'pagination'=>array(
                'pageSize'=>10
            )
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return User the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

    public function getActiveOptions()
    {
        if($this->active == 1)
        {
            return Yii::t('UserModule.base','Yes');
        }
        else
        {
            return Yii::t('UserModule.base','No');
        }
    }

    /**
     * Возвращает по id данные админа создавший пользователя
     * @return CActiveRecord
     */
    public function getCreateUserIdOptions()
    {
        $criteria = new CDbCriteria();
        $criteria->select = 'name,login,role';
        $userData = $this->findByAttributes(array('id'=>$this->create_user_id),$criteria);
        if($userData)
        {
            return $userData;
        }
        else
        {
           $userData = $this->findByAttributes(array('id'=>$this->id),$criteria);
           return $userData;
        }

    }

    /**
     * Возвращает по id данные админа обновивший пользователя
     * @return CActiveRecord
     */
    public function getUpdateUserIdOptions()
    {
        $criteria = new CDbCriteria();
        $criteria->select = 'name,login,role';
        $userData = $this->findByAttributes(array('id'=>$this->update_user_id),$criteria);

        if($userData)
        {
            return $userData;
        }
        else
        {
            $userData = $this->findByAttributes(array('id'=>$this->id),$criteria);
            return $userData;
        }

    }

    public function getActiveDropDownData()
    {
        return array('0'=>Yii::t('UserModule.base','No'),'1'=>Yii::t('UserModule.base','Yes'));
    }

    public function getRoleOptions()
    {
        return CHtml::listData(Yii::app()->authManager->getRoles(), 'name','name');
    }

    public function getImageForGrid()
    {
        if(isset($this->avatar) && file_exists(Yii::getPathOfAlias('webroot').'/images/avatar/'.$this->avatar))
        {
            return CHtml::link(CHtml::image('/images/avatar/'.$this->avatar,$this->avatar,array('class'=>'img-mini','data-toggle'=>'tooltip','title'=>$this->avatar)),Yii::app()->createUrl('/images/avatar/'.$this->avatar),array('class'=>'fancybox','rel'=>'group'));
        }
        return CHtml::image('/images/system/noimage.png','noimage.png',array('class'=>'img-mini','data-toggle'=>'tooltip','title'=>Yii::t('UserModule.base','No photo')));

    }
    public function getLoginTimeFormat()
    {
        if(isset($this->login_time))
        {
            return CLocale::getInstance(Yii::app()->getLocale()->id)->dateFormatter->formatDateTime(strtotime($this->login_time),'long','short');
        }
        return CHtml::tag('span',array('class'=>'label label-info'),Yii::t('UserModule.base','User has not logged.'));
    }
    public function getLastLoginTimeFormat()
    {
        if(isset($this->login_time))
        {
            return CLocale::getInstance(Yii::app()->getLocale()->id)->dateFormatter->formatDateTime(strtotime($this->last_login_time),'long','short');
        }
        return CHtml::tag('span',array('class'=>'label label-info'),Yii::t('UserModule.base','User has not logged.'));
    }
    public function getUpdateTime()
    {
        if(isset($this->update_time) && strtotime($this->update_time) !== strtotime($this->create_time))
        {
            return CLocale::getInstance(Yii::app()->getLocale()->id)->dateFormatter->formatDateTime(strtotime($this->update_time),'long','short');
        }
        return CHtml::tag('span',array('class'=>'label label-info'),Yii::t('UserModule.base','User has not updated.'));
    }
    public function getCreateTime()
    {
        if(isset($this->create_time))
        {
            return CLocale::getInstance(Yii::app()->getLocale()->id)->dateFormatter->formatDateTime(strtotime($this->create_time),'long','short');
        }
        return CHtml::tag('span',array('class'=>'label label-error'),Yii::t('UserModule.base','Undefined.'));
    }

    /*
     * Пытаемся получить аватарку
     */
    public function getAvatar()
    {
        if($this->avatar)
        {
            $path = Yii::getPathOfAlias('webroot').'/images/avatar/'.$this->avatar;
            if(file_exists($path))
            {
                return CHtml::image('/images/avatar/'.$this->avatar,'avatar',array('class'=>'img-thumbnail','style'=>'margin-left:25px'));
            }
            return CHtml::image('/images/system/image_not_found.png','avatar',array('class'=>'img-thumbnail','style'=>'margin-left:25px'));
        }
        else
        {
            return CHtml::image('/images/system/noavatar.png','avatar',array('class'=>'img-thumbnail','style'=>'margin-left:25px'));
        }

    }

    //Возврвщаем статус пользователя
    public function getIsActive()
    {
        if($this->active && Yii::app()->user->id === $this->id)
        {
            return CHtml::htmlButton(CHtml::tag('i',array('class'=>'fa fa-check green font16')),array('id'=>$this->id,'class'=>'btn btn-mini admin','title'=>Yii::t('UserModule.base','You can not block your own account'),'data-toggle'=>'tooltip'));
        }
        if($this->active)
        {
            return CHtml::htmlButton(CHtml::tag('i',array('class'=>'fa fa-check green font16')),array('id'=>$this->id,'class'=>'btn btn-mini','title'=>Yii::t('UserModule.base','Activated'),'data-toggle'=>'tooltip'));
        }
        return CHtml::htmlButton(CHtml::tag('i',array('class'=>'fa fa-times-circle red font16')),array('id'=>$this->id,'class'=>'btn btn-mini','title'=>Yii::t('UserModule.base','Unlock'),'data-toggle'=>'tooltip'));
    }

}
